package com.huiminpay.merchant.service;

import com.huiminpay.common.cache.domain.CommonErrorCode;
import com.huiminpay.common.cache.exception.BusinessException;
import com.huiminpay.common.cache.util.QRCodeUtil;
import com.huiminpay.transaction.api.TransactionServiceApi;
import com.huiminpay.transaction.api.dto.QRCodeDto;
import com.yh.merchant.api.MerchantServiceApi;
import com.yh.merchant.dto.MerchantDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @Author: HWW
 * @Date: 2021/8/3112:41
 * @Desc:
 */
@Service
@Slf4j
public class StoreService {

    @Reference
    private TransactionServiceApi transactionServiceApi;

    @Reference
    private MerchantServiceApi merchantServiceApi;

    /**
     * 门店二维码订单标题
     */
    @Value("${huiminpay.c2b.subject}")
    private String subject;
    /**
     * 门店二维码订单内容
     */
    @Value("${huiminpay.c2b.body}")
    private String body;


    public String getStoreQRCode(QRCodeDto qrCodeDto) throws Exception {
        //商户信息
        MerchantDTO merchantDTO = merchantServiceApi.queryMerchantById(qrCodeDto.getMerchantId());
        // 生成二维码链接
        //标题   用商户名称替换 %s
        String subjectFormat = String.format(subject, merchantDTO.getMerchantName());
        qrCodeDto.setSubject(subjectFormat);

        //内容,格式："向%s 付款"
        String bodyFormat = String.format(body, merchantDTO.getMerchantName());
        qrCodeDto.setBody(bodyFormat);

        //获取二维码的URL
        String storeQRCodeUrl = transactionServiceApi.createStoreQRCode(qrCodeDto);
        log.info("[merchantId:{},appId:{},storeId:{}]createCScanBStoreQRCode is {}",qrCodeDto.toString(),storeQRCodeUrl);

        try {
            //根据返回url，调用生成二维码工具类，生成二维码base64返回
            QRCodeUtil qrCodeUtil = new QRCodeUtil();
            //二维码图片base64编码
            String qrCode = qrCodeUtil.createQRCode(storeQRCodeUrl, 200, 200);

            return qrCode;

        } catch (IOException e) {

            throw new BusinessException(CommonErrorCode.E_200007);

        }

    }
}
